# -*- coding: utf-8 -*-

#
# peerscape.ftp.server
#
# Copyright 2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors:
#       Konrad Markus <konrad.markus@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os
import logging
from optparse import OptionParser

from peerscape import DB, PATH
from peerscape.ftp import DBFS, DBAuthorizer, DBFTPHandler, DBDTPHandler
from pyftpdlib import ftpserver

def serve(path, host, port):
    ftpserver.log = logging.debug
    ftpserver.logline = logging.debug

    # Instantiate a dummy authorizer for managing 'virtual' users
    theauthorizer = DBAuthorizer()

    # Define an anonymous user. 
    # The permissions are not actually governed by the below,
    # but rather by Peerscape internal permissions. (elr)
    theauthorizer.add_anonymous('/', perm='elradfmw')

    '''
    # Configure FTP handler class
    ftp_handler = ftpserver.FTPHandler
    ftp_handler.authorizer = authorizer
    ftp_handler.abstracted_fs = lambda: DBFS(path)
    '''

    class MyFTPHandler(DBFTPHandler):
        dtp_handler = DBDTPHandler
        authorizer = theauthorizer
        banner = "Peerscape FTPd"
        def abstracted_fs(self):
            return DBFS(path)


    # Instantiate FTP server class and listen to 127.0.0.1:21
    address = ('127.0.0.1', port)
    ftpd = ftpserver.FTPServer(address, MyFTPHandler)

    # set a limit for connections
    ftpd.max_cons = 256
    ftpd.max_cons_per_ip = 5

    # start ftp server
    try:
        logging.info('starting ftpd daemon on port %s...' % port)
        ftpd.serve_forever()
    except KeyboardInterrupt:
        pass


def main():
    logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

    parser = OptionParser()

    server_host = 'localhost'
    parser.add_option('--h', dest='server_host', default=server_host,
                      help='server host (default is %s)' % server_host)

    server_port = '21'
    parser.add_option('--p', dest='server_port', default=server_port,
                      help='server port (default is %s)' % server_port)

    parser.add_option('--db', dest='database_path', default=PATH,
                      help='location of database (default is %s)' % PATH)

    options, args = parser.parse_args()
    if args:
        parser.error('incorrect number of arguments')

    # resolve ~ in path
    options.database_path = os.path.expanduser(options.database_path)
    if not os.path.exists(options.database_path):
        logging.error('Database does not exist: %s' % options.database_path)
        exit(1)
    else:
        logging.info('database path is: %s' % options.database_path)

    serve(options.database_path, options.server_host, int(options.server_port))


if __name__ == '__main__':
    main()


